# Creates data used for different vignettes

### Switch function; takes input party name, returns number in coding

party.num <- function(party="ovp"){
  
  num <- switch(party
         ,ovp = 1
         ,spo = 2
         ,gruene = 3
         ,fpo = 4
         ,bzo = 5
         ,hans=6
         ,party)

  return(num)
  }



### Function That creates the Data

# Get's Data for Party1-Party Coalition Model.

Model.data <- function(
  party = "spo" ,coalition = "gruene" ,vig = "wahl3"
  ,rat.coal = "rat.spo.gruene"  
  ,data = oest ,sp="lr.s" ,pos="lr." ,rat="rat."
  ,covariates=c("gender","educ","relig"
               ,"union","income","age")
  ,drop.na=FALSE
){

  party <- party.num(party)
  coal <- party.num(coalition)
  
  # Y Choice Variable
  
  if(drop.na==TRUE) {data[vig][data[vig] > 96] <- NA}
  
  
  data$Y <- NA
  data$Y[data$wahl1==party & data[vig]==party] <- 1
  data$Y[data$wahl1==party & data[vig]==coal] <- 2
  data$Y[data$wahl1==party  & data[vig]!=party & data[vig]!=coal] <- 3
  
  data$Y[data$wahl1==coal & data[vig]==party] <- 4
  data$Y[data$wahl1==coal & data[vig]==coal] <- 5
  data$Y[data$wahl1==coal  & data[vig]!=party & data[vig]!=coal] <- 6
  
  data$Y[data$wahl1!=party & data$wahl1!=coal & data[vig]==party] <- 7
  data$Y[data$wahl1!=party & data$wahl1!=coal & data[vig]==coal] <- 8
  data$Y[data$wahl1!=party & data$wahl1!=coal & data[vig]!=party & data[vig]!=coal] <- 9
  
  
  
  # Choice in first decision
  data$a1 <-NA
  data$a1[data$wahl1==party] <- 1 
  data$a1[data$wahl1==coal] <- 2 
  data$a1[data$wahl1!=coal & data$wahl1!=party] <- 3 
  
  data$a2 <-NA
  data$a2[data[vig]==party] <- 1 
  data$a2[data[vig]==coal] <- 2 
  data$a2[data[vig]!=coal & data[vig]!=party] <- 3 
  
  
  # subset data to omit missings
  pp <- grep(paste(pos,party,sep=""),names(data),value=TRUE)
  pc <- grep(paste(pos,coal,sep=""),names(data),value=TRUE)
  rp <- grep(paste(rat,party,sep=""),names(data),value=TRUE)
  rc <- grep(paste(rat,coal,sep=""),names(data),value=TRUE)
  
  
  # Model 
  ####################
  
  # Subset 
  # Lr distance
  data$lr1 <- as.numeric(-(data[sp] - data[pp])^2)
  data$lr2 <- as.numeric(-(data[sp] - data[pc])^2)
  
  # Subset Data
  if(rat.coal!="rat.spo.fpo"){
  data <-  subset(data,select=c("Y","a1","a2",rp,rc,"lr1","lr2",rat.coal
                         ,covariates))
  } else {
  data <-  subset(data,select=c("Y","a1","a2",rp,rc,"lr1","lr2"
                         ,covariates))
  } 
  #PID
   if(any(covariates=="PID")){
    data$Pid1[data["PID"]!=party] <- 0
    data$Pid1[data["PID"]==party] <- 1
    data$Pid2[data["PID"]!=coal] <- 0
    data$Pid2[data["PID"]==coal] <- 1    
     }
  
  # Omit missings
  data <- na.omit(data)
  
  # Return Data
  return(data)

}







